//index.js
const utils = require("../../utils/utils.js");
const biz = require("../../utils/bizUtils.js");
const listUtil = require("../../utils/listUtil.js");
const session = require("../../utils/session.js");
const toast = require("../../utils/toasts.js");
const wxm = require("../../utils/wechat_modules.js");
const com = require("../../utils/commonRequest.js");

import {
  req
} from "../../utils/api.js";

//获取应用实例
const app = getApp()
const globalData = app.globalData;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    list: [],
    hidden: true,
    scrollTop: 0,
    scrollHeight: 0,
    title: '',
    keyword: null,
    catId: null,
    orderRule: 'HOT',
    waiting: true,
    share_modal: false,
    noMore: false,
    banners: ['https://img.lingxing.site/jx/banner400_4_2.png'],
    isIphoneX: globalData.isIphoneX,
    showAllStaffs: false
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.info(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    if (options) {
      if (options.id) {
        this.setData({
          id: options.id
        });
      }

      if (options.from) {
        this.setData({
          from: options.from
        })
      }


      if (options.salesId) {
        this.setData({
          salesId: options.salesId
        })
        if (options.salesName) {}
      }

      if (options.index) {
        this.setData({
          index: options.index
        });
      }

      if (options.type) {
        this.setData({
          type: options.type,
        })
      }
    }

    session.login(this.refreshMe);
  },
  refreshMe: function(usr) {
    this.setData({
      user: usr
    });
    toast.showLoading();

    this.getData();
    this.getRates();
  },
  onShow: function() {},
  onShareAppMessage: function(res) {
    var obj = this.data.obj;
    var seller = this.data.seller;
    var url = '/pages/staffDetail/staffDetail?id=' + obj.id;
    var title = seller.name+obj.realName;
    if(obj.summary) {
      title+=':'+obj.summary;
    } else {
    }

    return wxm.baseShare(this, title, url);

  },
  getData() {
    var id = this.data.id;
    if (!id) {
      wxm.showModal({
        title: '教练不存在',
        content: '你查找的教练不存在',
        hideCancel: true,
        isIt: (true)
      }).then(() => {
        wx.navigateBack({

        })
        return;
      }).catch(() => { });
      return;
    }

    var that = this;
    req('/seller/staffDetail', {
      id: id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var item = res.result;
        item.rateScore = biz.rateScore(item.totalRateScore, item.totalRateCount);
        item.rates = biz.rates(item.rateScore);
        item.driveTimeStr = utils.calAge(item.driveTime);
        item.teachTimeStr = utils.calAge(item.teachTime);
        item.summary = '金牌教练·' + item.driveTimeStr + '年驾龄·' + item.teachTimeStr + '年教龄';
        item.rateTip = item.rateScore + '分';
        if (!item.rateScore) {
          item.rateTip = '无评分';
        }

        that.setData({
          obj:item
        });
        this.getSeller();
        this.getProducts();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  getSeller() {
    var id = this.data.obj.sellerId;
    var that = this;
    req('/seller/jxDetail', {
      id: id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        obj.addressStr = biz.addressStr(obj);
        obj.bizTime = obj.openTime + '-' + obj.closeTime;
        that.setData({
          seller:obj
        });
        that.getWorks();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  getProducts() {
    var id = this.data.obj.sellerId;
    var that = this;
    req('/product/queryJx', {
      sellerId: id,
      pageNo: 1,
      pageSize: 20,
      status: 'SALE',
      withActivity: true
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var list = res.result.list;
        var productsCount = res.result.page.totalRecords;

        if (list) {
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            item.addressStr = biz.addressStr(item);
            item.rateScore = biz.rateScore(item.totalRateScore, item.totalRateCount);
            item.rates = biz.rates(item.rateScore);
            item.distanceStr = '距您' + biz.disStr(item.distance);
            if (item.cover) {
              item.cover1 = item.cover.split(',')[0];
            }
          }
          that.setData({
            products: list,
            productsCount
          })
        }
      } else { }
    });
  },
  getRates() {
    var id = this.data.id;
    var that = this;
    req('/rate/query', {
      servantId: id,
      pageNo: 1,
      pageSize: 10
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var list = res.result.list;
        if (list) {
          var ratesCount = res.result.page.totalRecords;
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            item.timeStr = utils.tf('yyyy-M-d', item.createdTime);
            item.rates = biz.rates(item.scoreall);
            var score = item.scoreall;
            if (!item.content) {
              if (score > 3) {
                item.content = '强烈推荐！';
              } else if (score == 3) {
                item.content = '一般般！';
              } else {
                item.content = '体验差不推荐！';
              }
            }
          }
          that.setData({
            rates: list,
            ratesCount
          })
        }
      } else {}
    });
  },
  pushFormSubmit: function(e) {
    console.log(e);
    console.log("formId:" + e.detail.formId);
    com.saveFormId(e);
  },
  gotoMap: function() {
    var obj = this.data.seller;
    biz.gotoMap({
      title: obj.name,
      lat: obj.lat,
      lng: obj.lng,
      address: obj.addressStr
    });
  },
  tel: function() {
    wxm.makePhoneCall(this.data.seller.tel);
  },
  showAllStaffs: function() {
    var showAllStaffs = this.data.showAllStaffs;
    this.setData({
      showAllStaffs: !showAllStaffs
    })
  },
  gotoSellerDetail:function() {
    var seller = this.data.seller;
    wx.navigateTo({
      url: '/pages/sellerDetail/sellerDetail?id='+seller.id,
    })
  },
  previewWorks: function (e) {
    biz.previewWorks(e, this)
  },
  getWorks() {
    var id = this.data.seller.id;
    var that = this;
    biz.getWorks(id, that);
  },
  gotoHome: function () {
    biz.gotoPage('/pages/index/index');
  },
})